import React, { Fragment, useState, useEffect, useRef } from "react";
import { Modal, Form, Input, Radio, Select, message } from "antd";
import { getRequest, postRequest } from "../../../utils/http";

const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 },
};

/* eslint-disable no-template-curly-in-string */
const validateMessages = {
  required: "请输入${label}！",
  types: {
    email: "${label} is not a valid email!",
    number: "${label} is not a valid number!",
  },
  number: {
    range: "${label} must be between ${min} and ${max}",
  },
};

export default function CreateAndUpdate(props) {
  const { visible, changeData, changeModalState, dialogTitle, tableData, setIsUpdate } = props;

  const [form] = Form.useForm();
  const { Option } = Select;

  /* 类型改变 */
  const [resourceType, setResourceType] = useState("catalog");
  const [resourceText, setResourceText] = useState("目录");
  const changeType = e => {
    let text = "";
    e.target.value === "menu" ? (text = "菜单") : e.target.value === "catalog" ? (text = "目录") : (text = "按钮");
    setResourceType(e.target.value);
    setResourceText(text);
  };

  /* 弹出框数据 */
  const [confirmLoading, setConfirmLoading] = useState(false);

  /* 初始化表单数据 */

  /* 表单数据回显 */
  const formRef = useRef();
  const [initPage, setInitPage] = useState({ type: "catalog", parentId: { value: "topLevel" } });
  useEffect(() => {
    async function initPage() {
      try {
        let url = `/resource/${changeData._id}`;
        const data = await getRequest(url);
        form.setFieldsValue(data);
        setInitPage(data);
      } catch (e) {
        message.error(e);
      }
    }
    changeData && initPage();
  }, [changeData, form]);

  /* 上级数据 */
  const [parentData, setParentData] = useState(null);
  useEffect(() => {
    getRequest("/resource/getAll").then(data => {
      setParentData(data);
    });
  }, []);

  /* 上级资源数据 */
  const [parentId, setParentId] = useState("topLevel");
  const selectParentId = key => {
    setParentId(key.value);
  };
  const [buttonParentId, setButtonParentId] = useState("noSelect");
  const selectButtonParentId = key => {
    setButtonParentId(key.value);
  };
  const [menuParentId, setMenuParentId] = useState("noSelect");
  const selectMenuParentId = key => {
    setMenuParentId(key.value);
  };

  /* 确认按钮 */
  const handleOk = () => {
    setConfirmLoading(true);
    form
      .validateFields()
      .then(values => {
        form.resetFields();
        values.parentId = parentId;
        let url = " /resource/create";
        changeData ? (url = `/resource/update/${changeData._id}`) : (url = "/resource/create");
        /* 数据提交 */
        postRequest(url, values).then(res => {
          let text = "";
          res.type === "menu" ? (text = "菜单") : res.type === "catalog" ? (text = "目录") : (text = "按钮");
          message.success(`${text}资源数据添加成功`);
          setIsUpdate(new Date().getTime());
          setResourceType("catalog");
          setResourceText("目录");
          setParentId("topLevel");
          form.resetFields();
        });
        changeModalState(false); // 关闭弹框
        setConfirmLoading(false); // 结束加载
      })
      .catch(info => {
        console.log("Validate Failed:", info);
        setConfirmLoading(false);
      });
  };

  /* 取消按钮 */
  const handleCancel = () => {
    changeModalState(false);
  };
  return (
    <Fragment>
      <Modal
        title={`${dialogTitle}资源`}
        visible={visible}
        width="660px"
        okText="提交"
        onOk={handleOk}
        confirmLoading={confirmLoading}
        cancelText="取消"
        onCancel={handleCancel}
        getContainer={false}
      >
        <Form
          {...layout}
          preserve={false}
          form={form}
          ref={formRef}
          name="form_in_modal"
          validateMessages={validateMessages}
          initialValues={initPage}
        >
          <Form.Item label="资源类型" name="type" className="collection-create-form_last-form-item">
            <Radio.Group onChange={changeType}>
              <Radio value="catalog">目录</Radio>
              <Radio value="menu">菜单</Radio>
              <Radio value="button">按钮</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label={`${resourceText}文字`} name="title" rules={[{ required: true }]}>
            <Input type="textarea" />
          </Form.Item>
          <Form.Item label="上一级目录" name="parentId" rules={[{ required: true }]}>
            <div style={{ display: "flex" }}>
              <Select
                style={{ marginRight: "10px" }}
                labelInValue
                value={{ value: parentId }}
                onSelect={selectParentId}
              >
                {parentData &&
                  parentData.map(
                    item =>
                      item.type === "catalog" && (
                        <Option key={item._id} value={item._id}>
                          {item.title}
                        </Option>
                      )
                  )}
              </Select>
              <Select
                style={{ marginRight: "10px" }}
                labelInValue
                value={{ value: menuParentId }}
                onSelect={selectMenuParentId}
              >
                <Option value="noSelect">请先上级目录</Option>
                {tableData.map(
                  item =>
                    item.type === "menu" &&
                    item.parentId === parentId && (
                      <Option key={item._id} value={item._id}>
                        {item.title}
                      </Option>
                    )
                )}
              </Select>
              <Select labelInValue value={{ value: buttonParentId }} onSelect={selectButtonParentId}>
                <Option value="noSelect">请先上级菜单</Option>
                {tableData.map(
                  item =>
                    item.type === "button" && (
                      <Option key={item._id} value={item._id}>
                        {item.title}
                      </Option>
                    )
                )}
              </Select>
            </div>
          </Form.Item>
          {(resourceType === "menu" || resourceType === "catalog") && (
            <Form.Item
              label={`${resourceText}地址`}
              name="key"
              rules={[{ required: resourceType === "button" ? false : true }]}
            >
              <Input />
            </Form.Item>
          )}
          {resourceType === "menu" && (
            <Form.Item label={`组件名称`} name="componentName" rules={[{ required: true }]}>
              <Input type="textarea" />
            </Form.Item>
          )}
          <Form.Item label={`${resourceText}图标`} name="icon">
            <Input type="textarea" />
          </Form.Item>
        </Form>
      </Modal>
    </Fragment>
  );
}
